// pages/purchaseHall/purchaseFriend/mypurchaseDetails.js
import api from '../../../utils/api.js';//这个里面封装了request方法
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // yijia:false,//议价：改变
    hideshowFormOfferPopup:true,
    formId:'',
    formoffers:[
    //   {
    //   "saleuserId": "1",
    //   "formId": "2",
    //   "count": 300,
    //   "price": 0.7,
    //   "fromAddress": "湖南",
    //   "offerstatus": 2,
    //   "saleusername": "xp",
    //   "salehead": "",
    //   "formstatus": 0,
    //   "units": "个",
    //   "itemId": "10",
    //   "itemName": "鸡蛋",
    //   "image1": "https://dcdn.it120.cc/2021/07/15/f0a26c05-afee-4ea7-a410-d9cdee090a7d.png"
    // }
  ],
    formoffer:{ 
    "saleuserId": "3",
    "formId": "1",
    "count": 2000,
    "price": 0.9,
    "fromAddress": "云南",
    "offerstatus": 0,
    "saleusername": "kzr",
    "salehead": null,
    "formstatus": 0,
    "itemId": "1",
    "itemName": "西瓜",
    "image": "https://dcdn.it120.cc/2021/07/15/b1763660-78bd-4a2d-bbae-9e68dc76bdbc.png",
    // status:0,
},
    form:{
      "formId": "1",
      "userId": "1",
      "catId": "1",
      "itemId": "1",
      "cycle": "day",
      "count": 2000,
      "receiptAddress": "湖南",
      "expectedAddress": "河北",
      "price": 2.0,
      "description": null,
      "offercount": 1,
      "status": 0,
      "units": "斤",
      "ddl": "2021-07-15",
      "totalcount": 2000,
      "itemName": "西瓜",
      "categoryId": "1",
      "image1": "https://dcdn.it120.cc/2021/07/15/b1763660-78bd-4a2d-bbae-9e68dc76bdbc.png",
      "image2": null
  },
    createTabs: true, //绘制tabs
    tabs: [{
      tabs_name: '采购商品',
      view_id: 'swiper-container',
      topHeight: 0
    }, {
      tabs_name: '采购详情',
      view_id: 'page__bd',
      topHeight: 0,
    },
    {
      tabs_name: '接单详情',
      view_id: 'goods-des-info',
      topHeight: 0,
    }],
    formoffersIndex:10,
    
    steps: [
      {
        text: '已报价',
        desc: '',
      },
      {
        text: '议价中',
        desc: '',
      },
      {
        text: '等待确认',
        desc: '',
      },
      {
        text: '已完成',
        desc: '',
      },
    ],
  },
  onTabsChange(e) {
    var index = e.detail.index
    this.setData({
      toView: this.data.tabs[index].view_id
    })
  },

  //formoffer状态变为1 未
  yijia(){
    //议价
    //首先改变数据库 
    const url = 'formOffers/forms/'+this.data.formId +'/users/'+this.data.formoffer.saleuserId+'?status=1';
    api.put(url).then(res => {
          //得到的数据
          let { code, data, msg } = res;
          console.log(res);
          
          // wx.showToast({
          //   title: msg,
          //   icon: 'none'
          // })

        }).catch(err => {
          console.log(err)
          // wx.showToast({
          //   title: "请求错误",
          //   icon: 'none'
          // })
        })
    //再改变当前页面
    this.setData({['formoffer.offerstatus']:1})
   
    //更新offers
    this.getFormOffers();
    wx.showModal({
      title: '提示',
      content: '请求议价成功，请协商后等待供应商再次给出价格！',
      success: function (res) {
        if (res.confirm) {//这里是点击了确定以后
          console.log('用户点击确定')

        } else {//这里是点击了取消以后
          console.log('用户点击取消')
        }
      }
    })
    console.log(this.data.formoffers)

  },
  //formoffer状态改变，form的count改变,如果formcount=0,form完成 未
  confirmPurchase(){
    console.log("确认采购此商家")//生成供货单
    var _this = this;
    if(this.data.formoffer.offerstatus == 1){
      wx.showModal({
        title: '提示',
        content: '议价中，请等待供货商选择敲定最终价格',
      })
    }
    if(this.data.formoffer.offerstatus == 0){
      wx.showModal({
        title: '提示',
        content: '确认选择该供货商？',
        success: function (res) {
          if (res.confirm) {//这里是点击了确定以后
            console.log('用户点击确定')
            //首先改变数据库 
            console.log(_this);
            console.log(this)
    const url = 'formOffers/forms/'+_this.data.formId +'/users/'+_this.data.formoffer.saleuserId+'?status=2';
    api.put(url).then(res => {
          //得到的数据
          let { code, data, msg } = res;
          console.log(res);

        }).catch(err => {
          console.log(err)

        })
    //再改变当前页面
    _this.setData({['formoffer.offerstatus']:2})
          } else {//这里是点击了取消以后
            console.log('用户点击取消')
            wx.showToast({
              title: "操作已取消",
              icon: 'none'
            })
          }
        }
      })
      //更新offers
    this.getFormOffers();
    console.log(this.data.formoffers)
    }
  

  },

  //删掉该formoffer 未
  cancelPurchase(){
    console.log("不采购此商家")
    wx.showModal({
      title: '提示',
      content: '此订单将不考虑该商户的供应，确认继续？',
      success: function (res) {
        if (res.confirm) {//这里是点击了确定以后
          console.log('用户点击确定')

        } else {//这里是点击了取消以后
          console.log('用户点击取消')
        }
      }
    })
    
  },
  //未
  cancelForm(){
    console.log("取消采购订单");
    if(this.data.form.totalcount != this.data.form.count){
      wx.showModal({
        title: '提示',
        content: '已获得部分供应，无法取消采购？',
      })
      return;
    }

    wx.showModal({
      title: '提示',
      content: '确认取消该采购订单吗？',
      success: function (res) {
        if (res.confirm) {//这里是点击了确定以后
          console.log('用户点击确定')

        } else {//这里是点击了取消以后
          console.log('用户点击取消')
        }
      }
    })

  },
  changeOfferStatus(){
    //改变订单状态,
    console.log("yijia");
    console.log(this.data.formoffer)
    this.setData({['formoffer.status']:1})
    console.log(this.data.formoffer)
  },


  showFormOffer(event){
    console.log("showFormOffer");
    console.log(event.currentTarget.id)

    let temp = this.data.formoffers[event.currentTarget.id]
    console.log(temp)
    this.setData({hideshowFormOfferPopup:false,
    formoffer:temp})

  },
  closePopupTap(){
    this.setData({hideshowFormOfferPopup:true})
  },
  bindscroll(e) {
    //计算页面 轮播图、详情、评价(砍价)view 高度
    this.getTopHeightFunction()
    var tabsHeight = this.data.tabsHeight //顶部距离（tabs高度）
    if (this.data.tabs[0].topHeight-tabsHeight<=0 && 0 < this.data.tabs[1].topHeight-tabsHeight) { //临界值，根据自己的需求来调整
      this.setData({
        active: this.data.tabs[0].tabs_name //设置当前标签栏
      })
    } else if (this.data.tabs[1].topHeight-tabsHeight<=0) {
      this.setData({
        active: this.data.tabs[1].tabs_name
      })
    }
  },
  getTopHeightFunction() {
    var that = this
    var tabs = that.data.tabs
    tabs.forEach((element, index) => {
      var viewId = "#" + element.view_id
      that.getTopHeight(viewId, index)
    });
  },
  getTopHeight(viewId, index) {
    var query = wx.createSelectorQuery();
    query.select(viewId).boundingClientRect((rect) => {
      if (!rect) {
        return
      }
      let top = rect.top
      var tabs = this.data.tabs
      tabs[index].topHeight = top
      this.setData({
        tabs: tabs
      })
    }).exec()
    
  },
   //初始化form数据
  getform(){
    let url = 'forms/'+this.data.formId;
    api.get(url,{
      data:''
    }).then(res => {
     //得到的数据
     console.log(res)
     this.setData({form:res.data})
     var limit = this.data.form.totalcount * 0.2
     let formIdTemp = this.data.form.formId
     this.setData({ buyNumber:limit,
                    formId:formIdTemp
           })
      console.log(this.data.formId)
     console.log(this.data.form);
     wx.showToast({
       title: '加载成功',
       icon: 'none'
     })
   }).catch(err => {
     console.log(err)
     wx.showToast({
       title: "请求错误",
       icon: 'none'
     })
   })

  },
  getFormOffers(){
   //初始化formoffers
   let url = 'formOffers/forms/'+this.data.formId;
   api.get(url).then(res => {
    //得到的数据
    let { code, data, msg } = res;
    console.log(res);
    this.setData({formoffers:res.data})
    // wx.showToast({
    //   title: msg,
    //   icon: 'none'
    // })

  }).catch(err => {
    console.log(err)
    // wx.showToast({
    //   title: "请求错误",
    //   icon: 'none'
    // })
  })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log("onload")
    this.setData({formId:options.formId});

    this.getform();
    this.getFormOffers();
   
    


    

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.getform();
    this.getFormOffers();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getform();
    this.getFormOffers();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    this.getform();
    this.getFormOffers();
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    this.getform();
    this.getFormOffers();
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.getform();
    this.getFormOffers();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    this.getform();
    this.getFormOffers();
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})